from elasticsearch import Elasticsearch


class EsOperate:
    def __init__(self, url, index):
        self.es = Elasticsearch([url])
        self.index = index
        self.__indexEs()

    # 创建Index
    def __indexEs(self):
        self.es.indices.create(index=self.index, ignore=400)

    # 插入数据
    def writeEs(self, doc_type, data):
        result = self.es.index(index=self.index, doc_type=doc_type, body=data)
        print(result)


if __name__ == "__main__":
    url = '192.168.3.109:9200'
    EsOperate = EsOperate(url, 'library')
    doc_type = 'book'
    id = 1
    datas = [
        {
            'name': "在远远的背后带领",
            'auth': "安心",
            'brief': "书名：在远远的背后带领"
        },
        {
            'name': "毓老师说论语",
            'auth': "爱新觉罗·毓鋆",
            'brief': "书名：毓老师说论语"
        },
        {
            'name': "隐秘战争",
            'auth': "阿里·拉伊迪",
            'brief': "书名：隐秘战争"
        }
    ]
    for data in datas:
        EsOperate.writeEs(doc_type, data)
        id += 1
